local Class = require("Core.Class")
local Coroutine = require("Core.Coroutine")
local ResManager = require("Game.Manager.ResManager")
local CoroutineManager = CS.GameCore.CoroutineManager.Instance

--- @Class LoadLevelManager
local LoadLevelManager = Class("LoadLevelManager")

function LoadLevelManager:OnInit()
    self.MapRootTr = CSE.GameObject.Find("MapRoot").transform
    self.MapItemsTr = self.MapRootTr:Find('MapItems')
    self.PlayersTr = self.MapRootTr:Find('Players')
end

function LoadLevelManager:LoadLevel(levelIndex, gameMode, onSuccess)
    local coroutine = Coroutine.Create(bind(LoadLevelManager.LoadMapAsyn, self), levelIndex, gameMode, onSuccess)
    CoroutineManager:StartCoroutine(coroutine)
end

function LoadLevelManager:LoadMapAsyn(levelIndex, gameMode, onSuccess)
    local mapData = require('Game.LevelMapItemPositionTable.Level'..levelIndex)
    local loadMapItemNum = 0

    -- 读取基地
    local homePosition = require('Game.LevelMapItemPositionTable.HomePoint')
    ResManager.LoadGameObject('Assets/GameRes/Prefabs/MapItem/Home.prefab',
        CSE.Vector3(homePosition[1], homePosition[2], 0), CSE.Quaternion.identity, function (obj)
            obj.transform:SetParent(self.MapItemsTr)
    end)
    coroutine.yield(nil)

    -- 读取玩家
    local playerPosition = require('Game.LevelMapItemPositionTable.PlayerBirthPoint')
    ResManager.LoadGameObject('Assets/GameRes/Prefabs/Player/Player1.prefab',
        CSE.Vector3(playerPosition[1][1], playerPosition[1][2], 0), CSE.Quaternion.identity, function (obj)
            obj.transform:SetParent(self.PlayersTr)
    end)
        if(gameMode == 2) then
            ResManager.LoadGameObject('Assets/GameRes/Prefabs/Player/Player2.prefab',
            CSE.Vector3(playerPosition[2][1], playerPosition[2][2], 0), CSE.Quaternion.identity, function (obj)
                obj.transform:SetParent(self.PlayersTr)
        end)
    end
    coroutine.yield(nil)

    -- 读取地图元素
    for key, value in pairs(mapData) do
        for i = #value, 1, -1 do
            ResManager.LoadGameObject('Assets/GameRes/Prefabs/MapItem/'..key..'.prefab',
                CSE.Vector3(value[i][1], value[i][2], 0), CSE.Quaternion.identity, function (obj)
                    obj.transform:SetParent(self.MapItemsTr)
            end)

            -- 每帧加载50块, 防止卡顿
            loadMapItemNum = loadMapItemNum + 1
            if(loadMapItemNum >= 50) then
                loadMapItemNum = 0
                coroutine.yield(nil)
            end
        end
    end

    -- 加载完成回调
    onSuccess()
end

function LoadLevelManager:DeleteMap()
    for i = self.PlayersTr.childCount - 1, 0, -1 do
        CSE.GameObject.Destroy(self.PlayersTr:GetChild(i).gameObject)
    end

    for i = self.MapItemsTr.childCount - 1, 0, -1 do
        CSE.GameObject.Destroy(self.MapItemsTr:GetChild(i).gameObject)
    end
end

return LoadLevelManager.New()